package bp.nbport;

import bp.da.*;
import bp.port.DeptEmpStation;
import bp.port.Station;
import net.sf.json.JSONObject;

public class OrgEmpCRUD {

    private String orgNo = "1";
    private String orgName = "浙江海港";

    public void dealOrgEmp(String message) throws Exception {
        if (message == null || message.trim().isEmpty()) {
            throw new IllegalArgumentException("消息内容为空");
        }
        JSONObject jsonData;
        try {
            jsonData = JSONObject.fromObject(message);
        } catch (Exception ex) {
            throw new IllegalArgumentException("消息内容不是有效的JSON格式", ex);
        }

        // 判断是否有顶层组织存在，没有就增加
        dealOrgAndAdminer();

        String type = jsonData.optString("type", null);
        if (type == null) {
            throw new IllegalArgumentException("JSON中缺少type字段");
        }

        if ("ORG".equals(type)) {
            // 处理组织信息
            dealOrg(jsonData);
        } else if ("user".equals(type)) {
            // 处理用户信息
            dealEmp(jsonData);
        }
    }

    public void dealOrgAndAdminer() throws Exception {
        bp.wf.port.admingroup.Org org = new bp.wf.port.admingroup.Org();
        org.setNo(orgNo);
        if (org.RetrieveFromDBSources() == 0) {
            org.setName(orgName);
            org.setAdminer("admin");
            org.setAdminerName("管理员");
            org.Insert();
        }

        OrgAdminerForJC oa = new OrgAdminerForJC();
        oa.setMyPK(orgNo + "_" + "admin");
        if (oa.RetrieveFromDBSources() == 0) {
            oa.setOrgNo(orgNo);
            oa.setEmpNo("admin");
            oa.setEmpName("管理员");
            oa.Insert();
        }

        // 插入部门.
        bp.port.DeptEmp de = new bp.port.DeptEmp();
        de.setMyPK(orgNo + "_" + "admin");
        if (de.RetrieveFromDBSources() == 0) {
            de.setDeptNo(orgNo);
            de.setEmpNo("admin");
            de.setOrgNo(orgNo);
            de.setDeptName(orgName);
            de.Insert();
        }

        // 增加管理员部门
        bp.port.Dept dept = new bp.port.Dept();
        dept.setNo(orgNo);
        if (dept.RetrieveFromDBSources() == 0) {
            dept.setName(orgName);
            dept.setParentNo("0");
            dept.setOrgNo(orgNo);
            dept.Insert();
        }
    }

    public void dealOrg(JSONObject jsonData) throws Exception {
        if (jsonData == null) return;
        String action = jsonData.optString("action", null);
        String orgCode = jsonData.optString("orgCode", null);
        String orgNameVal = jsonData.optString("orgName", null);
        String parentCode = jsonData.optString("parentCode", null);

        if (action == null || orgCode == null) {
            throw new IllegalArgumentException("JSON中缺少action或orgCode字段");
        }

        if ("add".equals(action) || "update".equals(action)) {
            // 增加部门.
            bp.nbport.DeptForJC dept = new bp.nbport.DeptForJC();
            dept.setNo(orgCode);
            if (dept.RetrieveFromDBSources() == 0) {
                dept.setName(orgNameVal != null ? orgNameVal : "");
                dept.setParentNo(parentCode != null ? parentCode : "");
                dept.setOrgNo(orgNo);
                dept.Insert();
            } else {
                dept.setName(orgNameVal != null ? orgNameVal : "");
                dept.setParentNo(parentCode != null ? parentCode : "");
                dept.setOrgNo(orgNo);
                dept.Update();
            }

            // 更新可能存在的之前未同步的部门名称
            DataTable dt = DBAccess.RunSQLReturnTable("select * from port_DeptEmp where fk_dept ='" + dept.getNo() + "'");
            if (dt != null && dt.Rows != null && dt.Rows.size() > 0) {
                for (DataRow dr : dt.Rows) {
                    bp.port.DeptEmp de = new bp.port.DeptEmp();
                    de.setMyPK(dr.getValue("MyPK").toString());
                    de.RetrieveFromDBSources();
                    de.setDeptName(dept.getName());
                    de.Update();
                }
            }
        } else if ("delete".equals(action)) {
            if (orgCode != null) {
                bp.port.Dept dept = new bp.port.Dept(orgCode);
                dept.Delete();
            }
        }
    }

    public void dealEmp(JSONObject jsonData) {
        if (jsonData == null) return;
        String action = jsonData.optString("action", null);
        String userNo = jsonData.optString("mobile", null);
        String deptNo = jsonData.optString("orgCode", null);
        String name = jsonData.optString("name", "");
        String postName = jsonData.optString("postName", "");

        if (action == null || userNo == null || deptNo == null) {
            throw new IllegalArgumentException("JSON中缺少action、mobile或orgCode字段");
        }

        try {
            if ("add".equals(action) || "update".equals(action)) {
                bp.nbport.DeptForJC dept = new bp.nbport.DeptForJC();
                dept.setNo(deptNo);
                if (dept.RetrieveFromDBSources() == 0) {
                    dept.setName("未同步");
                    dept.setParentNo(orgNo);
                    dept.setOrgNo(orgNo);
                    dept.Insert();
                }

                // 增加人员信息.
                bp.nbport.EmpForJC emp = new bp.nbport.EmpForJC();
                emp.setNo(userNo);
                if (emp.RetrieveFromDBSources() == 0) {
                    emp.setName(name);
                    emp.setDeptNo(deptNo);
                    emp.setOrgNo(orgNo);
                    emp.Insert();
                }

                emp.SetValByKey("tel", userNo);
                emp.setName(name);
                emp.setDeptNo(deptNo);
                emp.Update();

                DBAccess.RunSQL("DELETE FROM Port_DeptEmp WHERE FK_Emp='" + userNo + "' AND FK_Dept='" + deptNo + "' AND OrgNo='" + orgNo + "'");
                DBAccess.RunSQL("DELETE FROM Port_DeptEmpStation WHERE FK_Emp='" + userNo + "' AND FK_Dept='" + deptNo + "' AND OrgNo='" + orgNo + "'");

                // 插入部门.
                bp.port.DeptEmp de = new bp.port.DeptEmp();
                de.setDeptNo(emp.getDeptNo());
                de.setEmpNo(userNo);
                de.setOrgNo(orgNo);
                de.setDeptName(dept.getName());
                de.setMyPK(de.getDeptNo() + "_" + userNo);

                Station st = new Station();
                // 更新角色.
                DataTable dt = null;
                if (postName != null && !postName.isEmpty()) {
                    dt = DBAccess.RunSQLReturnTable("select * from port_station where name ='" + postName + "'");
                }
                if (dt != null && dt.Rows.size() > 0) {
                    st.setNo(dt.Rows.get(0).getValue("No").toString());
                } else if (postName != null && !postName.isEmpty()) {
                    st.setName(postName);
                    st.setNo(DBAccess.GenerGUID());
                    st.setFKStationType("3");
                    st.setOrgNo(orgNo);
                    st.DirectInsert();
                }
                // 插入部门岗位关系.
                if (st.getNo() != null && !st.getNo().isEmpty()) {
                    DeptEmpStation des = new DeptEmpStation();
                    des.setDeptNo(deptNo);
                    des.setEmpNo(userNo);
                    des.setStationNo(st.getNo());
                    des.setOrgNo(orgNo);
                    des.setMyPK(de.getDeptNo() + "_" + des.getEmpNo() + "_" + des.getStationNo());
                    des.DirectInsert();

                    de.setStationNo(st.getNo());
                    de.setStationNoT(postName);
                    de.DirectInsert();
                }

                String sql = "UPDATE Port_Emp SET OrgNo='" + orgNo + "' WHERE No='" + emp.getNo() + "'";
                DBAccess.RunSQL(sql);

            } else if ("delete".equals(action)) {
                DBAccess.RunSQL("DELETE FROM Port_Emp WHERE No='" + userNo + "' AND FK_Dept='" + deptNo + "' AND OrgNo='" + orgNo + "'");
                DBAccess.RunSQL("DELETE FROM Port_DeptEmp WHERE FK_Emp='" + userNo + "' AND FK_Dept='" + deptNo + "' AND OrgNo='" + orgNo + "'");
                DBAccess.RunSQL("DELETE FROM Port_DeptEmpStation WHERE FK_Emp='" + userNo + "' AND FK_Dept='" + deptNo + "' AND OrgNo='" + orgNo + "'");
            }
        } catch (RuntimeException ex) {
            ex.getMessage();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}